/*
 * ========================================================
 * Copyright(c) 2014 杭州偶尔科技-版权所有
 * ========================================================
 * 本软件由杭州偶尔科技所有, 未经书面许可, 任何单位和个人不得以
 * 任何形式复制代码的部分或全部, 并以任何形式传播。
 * 公司网址
 * 
 * 			http://www.kkkd.com/
 * 
 * ========================================================
 */
package com.simon.mengkou.ui.activity;

import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.ouertech.android.agm.lib.base.future.core.AgnettyFuture;
import com.ouertech.android.agm.lib.base.future.core.AgnettyResult;
import com.ouertech.android.agm.lib.base.utils.UtilList;
import com.ouertech.android.agm.lib.base.utils.UtilString;
import com.ouertech.android.agm.lib.ui.base.MenuTxt;
import com.ouertech.android.agm.lib.ui.base.defaults.activity.BaseTopActivity;
import com.simon.mengkou.R;
import com.simon.mengkou.data.bean.base.Tag;
import com.simon.mengkou.future.base.OuerFutureListener;
import com.simon.mengkou.system.constant.CstOuer;
import com.simon.mengkou.system.global.OuerApplication;
import com.simon.mengkou.ui.adapter.SearchTagAdapter;
import com.simon.mengkou.ui.dialog.DeleteDialog;
import com.simon.mengkou.ui.view.flowlayout.FlowLayout;
import com.simon.mengkou.utils.UtilOuer;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * @author : Zhenshui.Xia
 * @since : 2016/3/16.
 * desc    : 搜索标签界面
 */
public class SearchTagActivity extends BaseTopActivity {
    //最多标签数
    private static final int MAX_TAGS = 10;
    //搜索
    @Bind(R.id.search_id_search)
    EditText mEtSearch;
    //标签
    @Bind(R.id.search_id_tags)
    FlowLayout mFlTags;
    //标签列表
    @Bind(R.id.search_id_list)
    ListView mLvList;

    private SearchTagAdapter mAdapter;
    private ArrayList<Tag> mTags;
    private List<Tag> mDefaultTags;


    @Override
    protected void initTop() {
        setTitle(R.string.search_tag_title);
        setNavigation(R.drawable.common_ic_left_nav, new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                UtilOuer.hideInputManager(SearchTagActivity.this);
                finish();
                return false;
            }
        });

        MenuTxt txt = new MenuTxt.MenuTxtBuilder(this)
            .setTitle(R.string.common_finish)
            .setListener(new MenuItem.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    if(UtilList.isEmpty(mTags)) {
                        UtilOuer.toast(SearchTagActivity.this, R.string.search_tag_tags_empty);
                    } else {
                        UtilOuer.hideInputManager(SearchTagActivity.this);
                        Intent intent = new Intent();
                        intent.putExtra(CstOuer.KEY.TAGS, mTags);
                        setResult(RESULT_OK, intent);
                        finish();
                    }

                    return false;
                }
            }).build();

        addMenu(txt);
    }

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_search_tag);
    }

    @Override
    protected void initViews() {
        ButterKnife.bind(this);

        //搜索
        mEtSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int arg1, KeyEvent keyEvent) {
                if (arg1 == EditorInfo.IME_ACTION_SEARCH) {
                    String key = mEtSearch.getText().toString().trim();
                    searchTag(key);
                }

                return false;
            }
        });


        mEtSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String key = mEtSearch.getText().toString().trim();
                if(UtilString.isBlank(key)) {
                    mAdapter.setList(mDefaultTags);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mAdapter = new SearchTagAdapter(this);
        mLvList.setAdapter(mAdapter);
        mLvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int count = UtilList.getCount(mTags);
                if(count > MAX_TAGS) {
                    UtilOuer.toast(SearchTagActivity.this, R.string.search_tag_max);
                    return;
                }

                Tag tag = mAdapter.getItem(position);
                if(count == 0) {
                    mTags = new ArrayList<Tag>();
                    mTags.add(tag);
                } else {
                    boolean flag = false;
                    for(Tag t : mTags) {
                        if(t.getName().equals(tag.getName())) {
                            flag = true;
                            break;
                        }
                    }

                    if(!flag) {
                        mTags.add(tag);
                    } else {
                        //标签已经被添加
                        UtilOuer.toast(SearchTagActivity.this,
                                getString(R.string.search_tag_exist, tag.getName()));
                    }
                }

                addTags();
            }
        });

        defaultTag();
    }

    /**
     * 添加标签
     */
    private void addTags() {
        mFlTags.removeAllViews();
        if(UtilList.isNotEmpty(mTags)) {
            mFlTags.setVisibility(View.VISIBLE);
            for(final Tag tag : mTags) {
                TextView tvTag = new TextView(this);
                tvTag.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
                tvTag.setBackgroundResource(R.drawable.share_order_ic_tag);
                tvTag.setSingleLine(true);
                tvTag.setEllipsize(TextUtils.TruncateAt.END);
                tvTag.setText(tag.getName());
                mFlTags.addView(tvTag);
                tvTag.setOnClickListener(new View.OnClickListener(){

                    @Override
                    public void onClick(View v) {
                        final DeleteDialog dialog = new DeleteDialog(SearchTagActivity.this, null);
                        dialog.setOnClickListener(
                                new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        //删除标签
                                        if(v.getId() == R.id.delete_id_delete) {
                                            mTags.remove(tag);
                                            addTags();
                                            dialog.dismiss();
                                        }
                                    }
                                });

                        dialog.showAtLocation(mFlTags, Gravity.CENTER, 0, 0);
                    }
                });
            }
        } else {
            mFlTags.setVisibility(View.GONE);
        }
    }

    /**
     * 默认标签
     */
    private void defaultTag() {
        AgnettyFuture future = OuerApplication.mOuerFuture.searchTag(
                "", 0, 100,
                new OuerFutureListener(this) {
                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);
                        mDefaultTags = (List<Tag>) result.getAttach();
                        mAdapter.setList(mDefaultTags);
                    }
                }) ;

        attachDestroyFutures(future);
    }


    /**
     * 搜索标签
     */
    private void searchTag(final String key) {
        final Tag tag = new Tag();
        tag.setName(key);

        AgnettyFuture future = OuerApplication.mOuerFuture.searchTag(
                key, 0, CstOuer.PAGE.DEFAULT_SIZE,
                new OuerFutureListener(this) {
                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);
                        List<Tag> tags = (List<Tag>) result.getAttach();

                        if(UtilList.isEmpty(tags)) {
                            tags = new ArrayList<Tag>();
                            tags.add(tag);
                        } else {
                            Tag flag = null;
                            for(Tag t : tags) {
                                if(key.equals(t.getName())) {
                                    flag = t;
                                    break;
                                }
                            }

                            if(flag != null) {
                                tag.setId(flag.getId());
                                tags.remove(flag);
                            }

                            tags.add(0, tag);
                        }

                        mAdapter.setList(tags);
                    }

                    @Override
                    public void onException(AgnettyResult result) {
                        super.onException(result);
                        List<Tag> tags = new ArrayList<Tag>();
                        tags.add(tag);
                        mAdapter.setList(tags);
                    }

                    @Override
                    public void onNetUnavaiable(AgnettyResult result) {
                        List<Tag> tags = new ArrayList<Tag>();
                        tags.add(tag);
                        mAdapter.setList(tags);
                    }
                }) ;

        attachDestroyFutures(future);
    }

}
